﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Sales;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.Business.Prod;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Bpt;
using ESOL.Business.ProcessingService;

namespace ESOL.WinUI.Sales
{
    public partial class frmMaintainProductPlanApplicationOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public SalesProdPlanApplicationEntity SelectedProdPlanApplication { get; set; }
        private List<SalesProdPlanApplicationItemEntity> DeleteList = new List<SalesProdPlanApplicationItemEntity>();
        private List<SalesProdPlanApplicationItemEntity> mListApplicationItems;
        private List<SalesOrderEntity> mListOrders;
        private List<SalesOrderItemEntity> mListOrderItems;
        #endregion

        #region Constructor
        public frmMaintainProductPlanApplicationOrder()
        {
            InitializeComponent();
            if (SelectedProdPlanApplication == null)
            {
                SelectedProdPlanApplication = new SalesProdPlanApplicationEntity();
                SelectedProdPlanApplication.ApplicationId = Guid.NewGuid().ToString();
            }
        }
        public frmMaintainProductPlanApplicationOrder(List<SalesProdPlanApplicationItemEntity> list, MstCustomerEntity customer)
        {
            InitializeComponent();
            if (SelectedProdPlanApplication == null)
            {
                SelectedProdPlanApplication = new SalesProdPlanApplicationEntity();
                SelectedProdPlanApplication.ApplicationId = Guid.NewGuid().ToString();
            }
            SetFieldsByCustomer(customer);
            mListApplicationItems = list;
        }
        #endregion

        #region Functions
        private void SetFieldsByCustomer(MstCustomerEntity customer)
        {
            if (customer != null)
            {
                txtCustomer.Tag = customer;
                txtCustomer.Text = customer.CustomerName;

                UICommonFunctions.BindContactGridCombobox(colCONTACT_ID, customer.CustomerId, true);
            }
            else
            {
                txtCustomer.Tag = null;
                txtCustomer.Text = "";
                UICommonFunctions.BindContactGridCombobox(colCONTACT_ID, "", true);
                txtDeliveryPlaceZipcode.Text = "";
            }
            //Set default fields by customer
            if (customer != null)
            {
                txtDeliveryPlace.Text = customer.ReceivedAddress;
                txtDeliveryPlaceZipcode.Text = customer.ZipCode;
            }
        }

        private void SetDataGridDetailByApplicationItems()
        {
            if (mListApplicationItems == null || mListApplicationItems.Count == 0)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            foreach (SalesProdPlanApplicationItemEntity entity in mListApplicationItems)
            {
                DataRow dr = dt.NewRow();
                dr["APPLICATION_ITEM_ID"] = Guid.NewGuid().ToString();
                dr["APPLICATION_ID"] = SelectedProdPlanApplication.ApplicationId;
                dr["PRODUCT_ID"] = entity.ProductId;
                dr["ORDER_ITEM_ID"] = entity.OrderItemId;
                dr["QTY"] = entity.Qty;
                dr["PRICE"] = entity.Price;
                dr["PRICE_TYPE"] = "PRICET01";
                dr["PRODUCT_SPEC_IN"] = entity.ProductSpecIn;
                dr["PRODUCT_SPEC_OUT"] = entity.ProductSpecOut;
                dr["MATERIAL"] = entity.Material;
                dr["DIAMETER_OUT"] = entity.DiameterOut;
                dr["DIAMETER_IN"] = entity.DiameterIn;
                dr["LENGTH"] = entity.Length;
                dr["UNIT"] = entity.Unit;
                dr["STATUS"] = "PASTATUS01";
                dr["CHECKING_TYPE"] = "CHECK01";
                dr["PACKAGE_TYPE"] = "PT02";
                dr["PRODUCT_TYPE"] = "AT01";
                dr["PRINT_BRAND"] = 1;
                dr["IS_FINISHED"] = 0;

                if (string.IsNullOrEmpty(entity.ProductId) == false)
                {
                    MstProductEntity mProduct = MstProductBs.GetMstProductTypeByID(entity.ProductId);
                    dr["PRODUCT_ID"] = entity.ProductId;
                    dr["PRODUCT_CODE"] = mProduct.ProductCode;
                    dr["MATERIAL"] = mProduct.Material;
                    dr["DIAMETER_OUT"] = mProduct.DiameterOut;
                    dr["DIAMETER_IN"] = mProduct.DiameterIn;
                    dr["LENGTH"] = mProduct.Length;
                    dr["UNIT"] = mProduct.Unit;
                }
                dt.Rows.Add(dr);
            }
            ResetTotalAmount();
        }

        private void SetProdPlanAppBySalesOrder(SalesOrderEntity order)
        {
            if (order == null)
            {
                return;
            }
            if (SelectedProdPlanApplication == null)
            {
                SelectedProdPlanApplication = new SalesProdPlanApplicationEntity();
                SelectedProdPlanApplication.ApplicationId = Guid.NewGuid().ToString();
            }
            SelectedProdPlanApplication.OrderId = order.OrderId;
            SelectedProdPlanApplication.CustomerId = order.CustomerId;
            SelectedProdPlanApplication.DepartmentId = order.OrderDepartment;
            SelectedProdPlanApplication.ApplicationPerson = order.OrderPerson;
            SelectedProdPlanApplication.DeliveryType = order.TransportType;
            SelectedProdPlanApplication.ApplicationDate = DateTime.Today;
            SelectedProdPlanApplication.PaymentType = order.PaymentType;
            SelectedProdPlanApplication.IsTax = order.IsTax;
            if (SelectedProdPlanApplication.IsTax == 1)
            {
                cboxIsTax.Checked = true;
            }
            SetFields();

            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                if (dr.RowState != DataRowState.Added)
                {
                    SalesProdPlanApplicationItemEntity entity = new SalesProdPlanApplicationItemEntity(dr);
                    DeleteList.Add(entity);
                }
                dt.Rows.Remove(dr);
            }
            List<SalesOrderItemEntity> list = SalesOrderItemBs.GetBySalesOrderID(order.OrderId);
            foreach (SalesOrderItemEntity entity in list)
            {
                DataRow dr = dt.NewRow();
                dr["APPLICATION_ITEM_ID"] = Guid.NewGuid().ToString();
                dr["APPLICATION_ID"] = SelectedProdPlanApplication.ApplicationId;
                dr["PRODUCT_ID"] = entity.ProductId;
                dr["ORDER_ITEM_ID"] = entity.OrderItemId;
                dr["QTY"] = entity.Qty;
                dr["PRICE"] = entity.PriceNoTax;
                dr["PRICE_TYPE"] = "PRICET01";
                dr["PRODUCT_SPEC_IN"] = entity.ProductSpecIn;
                dr["PRODUCT_SPEC_OUT"] = entity.ProductSpecOut;
                dr["MATERIAL"] = entity.Material;
                dr["DIAMETER_OUT"] = entity.DiameterOut;
                dr["DIAMETER_IN"] = entity.DiameterIn;
                dr["LENGTH"] = entity.Length;
                dr["UNIT"] = entity.Unit;
                dr["STATUS"] = "PASTATUS01";
                dr["CHECKING_TYPE"] = "CHECK01";
                dr["PACKAGE_TYPE"] = "PT02";
                dr["PRODUCT_TYPE"] = "AT01";
                dr["PRINT_BRAND"] = 1;
                dr["IS_FINISHED"] = 0;

                if (string.IsNullOrEmpty(entity.ProductId) == false)
                {
                    MstProductEntity mProduct = MstProductBs.GetMstProductTypeByID(entity.ProductId);
                    dr["PRODUCT_ID"] = entity.ProductId;
                    dr["PRODUCT_CODE"] = mProduct.ProductCode;
                    dr["MATERIAL"] = mProduct.Material;
                    dr["DIAMETER_OUT"] = mProduct.DiameterOut;
                    dr["DIAMETER_IN"] = mProduct.DiameterIn;
                    dr["LENGTH"] = mProduct.Length;
                    dr["UNIT"] = mProduct.Unit;
                }
                dt.Rows.Add(dr);
            }
            ResetTotalAmount();
        }

        private void SetDataGridDetailByListBox()
        {
            if (lboxContact.Tag == null || lboxContact.Tag.GetType() != typeof(List<SalesOrderEntity>))
            {
                return;
            }
            List<SalesOrderItemEntity> mListItems = new List<SalesOrderItemEntity>();
            List<SalesOrderEntity> mList = (List<SalesOrderEntity>)lboxContact.Tag;
            foreach (SalesOrderEntity entity in mList)
            {
                List<SalesOrderItemEntity> items = SalesOrderItemBs.GetBySalesOrderID(entity.OrderId);
                if (items != null && items.Count > 0)
                {
                    mListItems.AddRange(items);
                }


            }
            mListOrders = mList;
            mListOrderItems = mListItems;
            SetDataGridDetailBySalesOrderItems();
        }

        private void SetDataGridDetailBySalesOrderItems()
        {
            if (mListOrderItems == null || mListOrderItems.Count == 0)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (SalesOrderItemEntity entity in mListOrderItems)
            {
                DataRow dr = dt.NewRow();
                dr["APPLICATION_ITEM_ID"] = Guid.NewGuid().ToString();
                dr["APPLICATION_ID"] = SelectedProdPlanApplication.ApplicationId;
                dr["PRODUCT_ID"] = entity.ProductId;
                dr["ORDER_ITEM_ID"] = entity.OrderItemId;
                dr["QTY"] = entity.Qty;
                dr["PRICE"] = entity.PriceNoTax;
                dr["PRICE_TYPE"] = "PRICET01";
                dr["PRODUCT_SPEC_IN"] = entity.ProductSpecIn;
                dr["PRODUCT_SPEC_OUT"] = entity.ProductSpecOut;
                dr["MATERIAL"] = entity.Material;
                dr["DIAMETER_OUT"] = entity.DiameterOut;
                dr["DIAMETER_IN"] = entity.DiameterIn;
                dr["LENGTH"] = entity.Length;
                dr["UNIT"] = entity.Unit;
                dr["STATUS"] = "PASTATUS01";
                dr["CHECKING_TYPE"] = "CHECK01";
                dr["PACKAGE_TYPE"] = "PT02";
                dr["PRODUCT_TYPE"] = "AT01";
                dr["PRINT_BRAND"] = 1;
                dr["IS_FINISHED"] = 0;
                dr["ORDER_ITEM_ID"] = entity.OrderItemId;

                if (string.IsNullOrEmpty(entity.ProductId) == false)
                {
                    MstProductEntity mProduct = MstProductBs.GetMstProductTypeByID(entity.ProductId);
                    dr["PRODUCT_ID"] = entity.ProductId;
                    dr["PRODUCT_CODE"] = mProduct.ProductCode;
                    dr["MATERIAL"] = mProduct.Material;
                    dr["DIAMETER_OUT"] = mProduct.DiameterOut;
                    dr["DIAMETER_IN"] = mProduct.DiameterIn;
                    dr["LENGTH"] = mProduct.Length;
                    dr["UNIT"] = mProduct.Unit;
                }
                dt.Rows.Add(dr);
            }
            ResetTotalAmount();
        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbDeliveryType, "DW", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPaymentType, "PAYWAY", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbTrasportType, "TF", false);
            //UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbApplicationType, "AT", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbProductType, "PTYPE", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPACKAGE_TYPE, "PT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colCHECKING_TYPE, "CHECK", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colSTATUS, "PASTATUS", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPRODUCT_TYPE, "AT", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colDELIVERY_APPLICATION, "DA", false);
            UICommon.UICommonFunctions.BindGridComboboxByEnum(colPRINT_BRAND, typeof(BoolStatus), typeof(int), false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPRICE_TYPE, "PRICET", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }

        private void BindDataGridDetail()
        {
            if (SelectedProdPlanApplication == null)
            {
                gvMain.DataSource = null;
                return;
            }
            DataSet ds = SalesProdPlanApplicationItemBs.GetDataSetByAppID(SelectedProdPlanApplication.ApplicationId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvMain.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvMain.DataSource = dt;
            DeleteList = new List<SalesProdPlanApplicationItemEntity>();
        }

        private void ResetTotalAmount()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["PRICE"].ToString()) == false && string.IsNullOrEmpty(dr["QTY"].ToString()) == false)
                {
                    decimal qty = Convert.ToDecimal(dr["QTY"].ToString());
                    decimal price = Convert.ToDecimal(dr["PRICE"].ToString());
                    dr["TOTAL_AMOUNT"] = qty * price;
                }
            }
        }

        private void ResetTax()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["TOTAL_AMOUNT"] != null)
                {
                    decimal tax = Convert.ToDecimal(1.17);//CommonFunctions.ToDecimal(dr["TAX_RATE"]) + 1;
                    decimal price = CommonFunctions.ToDecimal(dr["PRICE"]);
                    if (cboxIsTax.Checked)
                    {
                        price = price * tax;
                    }
                    else
                    {
                        price = price / tax;
                    }
                    decimal amount = CommonFunctions.ToDecimal(dr["QTY"]) * price;
                    dr["PRICE"] = price.ToString("#0.00");
                    dr["TOTAL_AMOUNT"] = amount.ToString("#0.00");
                }
            }
        }

        private void SetFields()
        {
            if (SelectedProdPlanApplication == null)
            {
                BindDataGridDetail();
                return;
            }
            if (string.IsNullOrEmpty(SelectedProdPlanApplication.OrderId) == false)
            {
                SalesOrderEntity order = SalesOrderBs.GetSalesOrderByID(SelectedProdPlanApplication.OrderId);
                if (order != null)
                {
                    txtSalesOrder.Text = order.OrderCode;
                    txtSalesOrder.Tag = order;
                }
            }
            if (string.IsNullOrEmpty(SelectedProdPlanApplication.CustomerId) == false)
            {
                MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByID(SelectedProdPlanApplication.CustomerId);
                if (customer != null)
                {
                    SetFieldsByCustomer(customer);
                }
            }
            txtApplicationCode.Text = SelectedProdPlanApplication.ApplicationCode;
            if (string.IsNullOrEmpty(txtApplicationCode.Text))
            {
                txtApplicationCode.Text = "自动生成";
            }
            if (string.IsNullOrEmpty(SelectedProdPlanApplication.DepartmentId) == false)
            {
                MstDepartmentEntity department = MstDepartmentBs.GetMstDepartmentByID(SelectedProdPlanApplication.DepartmentId);
                if (department != null)
                {
                    txtDepartment.Tag = department;
                    txtDepartment.Text = department.DepartmentName;
                }
            }
            if (ThisActionType == ActionType.New)
            {
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(CommonParameter.CurrentUser.PersonId);
                if (person != null)
                {
                    txtApplicationPerson.Tag = person;
                    txtApplicationPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
                MstDepartmentEntity department = MstDepartmentBs.GetMstDepartmentByID(person.DepartmentId);
                if (department != null)
                {
                    txtDepartment.Text = department.DepartmentName;
                    txtDepartment.Tag = department;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(SelectedProdPlanApplication.ApplicationPerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedProdPlanApplication.ApplicationPerson);
                    if (person != null)
                    {
                        txtApplicationPerson.Tag = person;
                        txtApplicationPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
            }
            cmbPaymentType.SetSelectedValue(SelectedProdPlanApplication.PaymentType);
            cmbTrasportType.SetSelectedValue(SelectedProdPlanApplication.TrasportType);
            cmbDeliveryType.SetSelectedValue(SelectedProdPlanApplication.DeliveryType);
            if (SelectedProdPlanApplication.ApplicationDate != null)
            {
                dtpApplicationDate.EditValue = SelectedProdPlanApplication.ApplicationDate;
            }
            cmbStatus.SetSelectedValue(SelectedProdPlanApplication.Status);
            txtRemark.Text = SelectedProdPlanApplication.Remark;

            if (string.IsNullOrEmpty(SelectedProdPlanApplication.DeliveryPlace) == false)
            {
                txtDeliveryPlace.Text = SelectedProdPlanApplication.DeliveryPlace;
            }
            if (string.IsNullOrEmpty(SelectedProdPlanApplication.DeliveryPlaceZipcode) == false)
            {
                txtDeliveryPlaceZipcode.Text = SelectedProdPlanApplication.DeliveryPlaceZipcode;
            }
            if (SelectedProdPlanApplication.IsTax == 1)
            {
                cboxIsTax.Checked = true;
            }
            else
            {
                cboxIsTax.Checked = false;
            }
            cmbTrasportType.SetSelectedValue(SelectedProdPlanApplication.TrasportType);
            cmbProductType.SetSelectedValue(SelectedProdPlanApplication.ProductType);

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedProdPlanApplication.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedProdPlanApplication.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedProdPlanApplication.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedProdPlanApplication.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedProdPlanApplication.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedProdPlanApplication.ApprovedBy);

            DataTable relation = SalesOrderToAppBs.GetDtByAppId(SelectedProdPlanApplication.ApplicationId);
            if (relation != null && relation.Rows.Count > 0)
            {
                if (mListOrders != null)
                {
                    mListOrders.Clear();
                }
                else
                {
                    mListOrders = new List<SalesOrderEntity>();
                }
                lboxContact.Items.Clear();
                foreach (DataRow dr in relation.Rows)
                {
                    SalesOrderEntity order = SalesOrderBs.GetSalesOrderByID(dr["SALES_ORDER_ID"].ToString());
                    if (order != null)
                    {
                        mListOrders.Add(order);
                        lboxContact.Items.Add(order.OrderCode);
                    }
                }
                lboxContact.Tag = mListOrders;
            }

            BindDataGridDetail();
        }

        private decimal dTotalAmount = 0;
        private void SetEntity()
        {
            if (txtSalesOrder.Tag != null && txtSalesOrder.Tag.GetType() == typeof(SalesOrderEntity))
            {
                SelectedProdPlanApplication.OrderId = ((SalesOrderEntity)txtSalesOrder.Tag).OrderId;
            }
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                SelectedProdPlanApplication.CustomerId = ((MstCustomerEntity)txtCustomer.Tag).CustomerId;
            }
            if (txtDepartment.Tag != null && txtDepartment.Tag.GetType() == typeof(MstDepartmentEntity))
            {
                SelectedProdPlanApplication.DepartmentId = ((MstDepartmentEntity)txtDepartment.Tag).DepartmentId;
            }
            if (txtApplicationPerson.Tag != null && txtApplicationPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedProdPlanApplication.ApplicationPerson = ((MstPersonEntity)txtApplicationPerson.Tag).PersonId;
            }

            if (cmbPaymentType.SelectedValue != null && cmbPaymentType.SelectedValue.ToString().Trim() != "")
            {
                SelectedProdPlanApplication.PaymentType = cmbPaymentType.SelectedValue.ToString().Trim();
            }
            if (cmbTrasportType.SelectedValue != null && cmbTrasportType.SelectedValue.ToString().Trim() != "")
            {
                SelectedProdPlanApplication.TrasportType = cmbTrasportType.SelectedValue.ToString().Trim();
            }
            if (cmbDeliveryType.SelectedValue != null && cmbDeliveryType.SelectedValue.ToString().Trim() != "")
            {
                SelectedProdPlanApplication.DeliveryType = cmbDeliveryType.SelectedValue.ToString().Trim();
            }
            if (dtpApplicationDate.EditValue != null)
            {
                SelectedProdPlanApplication.ApplicationDate = Convert.ToDateTime(dtpApplicationDate.EditValue);
            }
            SelectedProdPlanApplication.Remark = txtRemark.Text;
            SelectedProdPlanApplication.DeliveryPlace = txtDeliveryPlace.Text;
            SelectedProdPlanApplication.DeliveryPlaceZipcode = txtDeliveryPlaceZipcode.Text;
            if (cmbTrasportType.SelectedValue != null && cmbTrasportType.SelectedValue.ToString().Trim() != "")
            {
                SelectedProdPlanApplication.TrasportType = cmbTrasportType.SelectedValue.ToString();
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt.Rows[0]["CONTACT_ID"] != null && dt.Rows[0]["CONTACT_ID"].ToString().Trim() != "")
            {
                SelectedProdPlanApplication.ContactId = dt.Rows[0]["CONTACT_ID"].ToString();
            }
            SelectedProdPlanApplication.TotalAmount = Convert.ToDecimal(dt.Compute("sum(TOTAL_AMOUNT)", null).ToString());
            if (cmbProductType.SelectedValue != null && cmbProductType.SelectedValue.ToString().Trim() != "")
            {
                SelectedProdPlanApplication.ProductType = cmbProductType.SelectedValue.ToString();
            }
            if (ThisActionType == ActionType.New)
            {
                SelectedProdPlanApplication.CreatedDate = DateTime.Now;
                SelectedProdPlanApplication.CreatedBy = CommonParameter.CurrentUser.PersonId;
                SelectedProdPlanApplication.Status = "STATUS02";
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedProdPlanApplication.LastModifiedDate = DateTime.Now;
                SelectedProdPlanApplication.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }

        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtCustomer.Text))
            {
                MessageBox.Show("客户简称不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtDepartment.Text))
            {
                MessageBox.Show("申请部门不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtApplicationPerson.Text))
            {
                MessageBox.Show("申请人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpApplicationDate.EditValue == null
                || dtpApplicationDate.EditValue.ToString().Equals("0001-01-01 0:00:00"))
            {
                MessageBox.Show("申请日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbTrasportType.SelectedValue == null || cmbTrasportType.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("运输费用不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbPaymentType.SelectedValue == null || cmbPaymentType.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("付款方式不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbDeliveryType.SelectedValue == null || cmbDeliveryType.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("发货方式不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gvMain.DataSource == null)
            {
                MessageBox.Show("生产计划申请单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("生产计划申请单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            string msg = "";
            if (UICommonFunctions.CheckDataGrid(gvMain, out msg) == false)
            {
                MessageBox.Show(msg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = SalesProdPlanApplicationBs.SaveProdPlanApplication(true, SelectedProdPlanApplication, dt, DeleteList, mListOrders);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = SalesProdPlanApplicationBs.SaveProdPlanApplication(false, SelectedProdPlanApplication, dt, DeleteList, mListOrders);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SetEntity();
                    string msg = "";
                    if (SalesToPlan.ApproveSalesApplication(SelectedProdPlanApplication, out msg) == false)
                    {
                        MessageBox.Show("审核失败！" + msg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                    //DataTable dt = (DataTable)gvMain.DataSource;
                    //bool isSuccessful_modify = SalesProdPlanApplicationBs.SaveProdPlanApplication(false, SelectedProdPlanApplication, dt, DeleteList);
                    //if (isSuccessful_modify)
                    //{
                    //    SelectedProdPlanApplication.ApprovedDate = DateTime.Now;
                    //    SelectedProdPlanApplication.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    //    //bool isSuccessful = SalesProdPlanApplicationBs.UpdateSalesProdPlanApplication(SelectedProdPlanApplication);
                    //    string sErrMsg = "";
                    //    bool isSuccessful = ProdPlanOrderBs.ApproveProdPlanApplication(SelectedProdPlanApplication,out sErrMsg);
                    //    if (!isSuccessful)
                    //    {
                    //        if (string.IsNullOrEmpty(sErrMsg) == false)
                    //        {
                    //            MessageBox.Show("审核失败！"+sErrMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //            return false;
                    //        }
                    //        else
                    //        {
                    //            MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //            return false;
                    //        }                            
                    //    }
                    //}
                    //else
                    //{
                    //    MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //    return false;
                    //}

                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void ResetContactColumn()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                dr["CONTACT_ID"] = null;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            SetFields();
            SetDataGridDetailByApplicationItems();
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedProdPlanApplication = new SalesProdPlanApplicationEntity();
                SelectedProdPlanApplication.ApplicationId = Guid.NewGuid().ToString();
                SetFields();
            }
        }

        protected override void Click_Approve()
        {
            if (SelectedProdPlanApplication == null)
            {
                return;
            }
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Reject()
        {
            if (SelectedProdPlanApplication == null)
            {
                return;
            }
            SelectedProdPlanApplication.Status = NormalStatus.STATUS04.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private DataRow drApplicaitonItemSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drApplicaitonItemSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        private void txtSalesOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSalesOrderQuery frm = new frmMaintainSalesOrderQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedSalesOrder != null)
            {
                txtSalesOrder.Text = frm.SelectedSalesOrder.OrderCode;
                txtSalesOrder.Tag = frm.SelectedSalesOrder;

                SetProdPlanAppBySalesOrder(frm.SelectedSalesOrder);
            }
            else
            {
                txtSalesOrder.Text = "";
                txtSalesOrder.Tag = null;
            }
        }

        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtApplicationPerson.Tag == null || txtApplicationPerson.Tag.GetType() != typeof(MstPersonEntity))
            {
                MessageBox.Show("请先选择业务员！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery((MstPersonEntity)txtApplicationPerson.Tag);
            ResetContactColumn();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCustomer != null)
            {
                SetFieldsByCustomer(frm.SelectedCustomer);
            }
            else
            {
                SetFieldsByCustomer(null);
            }
        }

        private void txtDepartment_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainDepartmentQuery frm = new frmMaintainDepartmentQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedDepartment != null)
            {
                txtDepartment.Text = frm.SelectedDepartment.DepartmentName;
                txtDepartment.Tag = frm.SelectedDepartment;
            }
            else
            {
                txtDepartment.Text = "";
                txtDepartment.Tag = null;
            }
        }

        private void txtApplicationPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (txtDepartment.Tag != null && txtDepartment.Tag.GetType() == typeof(MstDepartmentEntity))
            {
                frm = new frmMaintainEmployeeQuery((MstDepartmentEntity)txtDepartment.Tag);
            }
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtApplicationPerson.Text = frm.SelectedPerson.NameCn;
                txtApplicationPerson.Tag = frm.SelectedPerson;

                MstDepartmentEntity department = MstDepartmentBs.GetMstDepartmentByID(frm.SelectedPerson.DepartmentId);
                if (department != null)
                {
                    txtDepartment.Text = department.DepartmentName;
                    txtDepartment.Tag = department;
                }
            }
            else
            {
                txtApplicationPerson.Text = "";
                txtApplicationPerson.Tag = null;
            }
        }

        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            DataRow dr = dt.NewRow();
            dr["APPLICATION_ITEM_ID"] = Guid.NewGuid().ToString();
            dr["APPLICATION_ID"] = SelectedProdPlanApplication.ApplicationId;
            dr["PRICE_TYPE"] = "PRICET01";
            dr["STATUS"] = "PASTATUS01";
            dr["CHECKING_TYPE"] = "CHECK01";
            dr["PACKAGE_TYPE"] = "PT02";
            dr["PRODUCT_TYPE"] = "AT01";
            dr["PRINT_BRAND"] = 1;
            dr["IS_FINISHED"] = 0;
            dt.Rows.Add(dr);
            drApplicaitonItemSelected = gridView1.GetFocusedDataRow();
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            if (drApplicaitonItemSelected == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (drApplicaitonItemSelected.RowState != DataRowState.Added)
            {
                SalesProdPlanApplicationItemEntity entity = new SalesProdPlanApplicationItemEntity(drApplicaitonItemSelected);
                DeleteList.Add(entity);
            }
            dt.Rows.Remove(drApplicaitonItemSelected);
            ResetTotalAmount();
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drApplicaitonItemSelected == null)
            {
                return;
            }
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                drApplicaitonItemSelected["PRODUCT_ID"] = frm.SelectedProduct.ProductId;
                drApplicaitonItemSelected["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                drApplicaitonItemSelected["PRODUCT_SPEC_IN"] = frm.SelectedProduct.ProductSpecIn;
                drApplicaitonItemSelected["PRODUCT_SPEC_OUT"] = frm.SelectedProduct.ProductSpecOut;
                drApplicaitonItemSelected["MATERIAL"] = frm.SelectedProduct.Material;
                drApplicaitonItemSelected["DIAMETER_OUT"] = frm.SelectedProduct.DiameterOut;
                drApplicaitonItemSelected["DIAMETER_IN"] = frm.SelectedProduct.DiameterIn;
                drApplicaitonItemSelected["LENGTH"] = frm.SelectedProduct.Length;
                drApplicaitonItemSelected["UNIT"] = frm.SelectedProduct.Unit;
            }
            ////2012-12-31 杨+
            //if (cmbApplicationType.SelectedValue.ToString().Equals("AT03") && txtMaintainOrder.Tag != null)
            //{
            //    frmRepRegisterItemQuery frm = new frmRepRegisterItemQuery();
            //    frm.SelectedProductRegister = (RepProductRegisterEntity)txtMaintainOrder.Tag;
            //    if (frm.ShowDialog() == DialogResult.OK && frm.SelectedRepRegisterItem != null)
            //    {
            //        DataRowView view = (DataRowView)gvDetail.Rows[gvDetail.SelectedCells[0].RowIndex].DataBoundItem;
            //        DataRow dr = view.Row;
            //        if (string.IsNullOrEmpty(frm.SelectedRepRegisterItem.ProductId))
            //        {
            //            dr["PRODUCT_SPEC_IN"] = frm.SelectedRepRegisterItem.ProductSpecIn;
            //            dr["PRODUCT_SPEC_OUT"] = frm.SelectedRepRegisterItem.ProductSpecOut;
            //            dr["MATERIAL"] = frm.SelectedRepRegisterItem.Material;
            //            dr["DIAMETER_OUT"] = frm.SelectedRepRegisterItem.DiameterOut;
            //            dr["DIAMETER_IN"] = frm.SelectedRepRegisterItem.DiameterIn;
            //            dr["LENGTH"] = frm.SelectedRepRegisterItem.Length;
            //            dr["UNIT"] = frm.SelectedRepRegisterItem.Unit;
            //            dr["REGISTER_ITEM_ID"] = frm.SelectedRepRegisterItem.RegisterItemId;
            //        }
            //        else
            //        {
            //            MstProductEntity mProduct = MstProductBs.GetMstProductTypeByID(frm.SelectedRepRegisterItem.ProductId);
            //            dr["PRODUCT_ID"] = mProduct.ProductId;
            //            dr["PRODUCT_CODE"] = mProduct.ProductCode;
            //            dr["PRODUCT_SPEC_IN"] = mProduct.ProductSpecIn;
            //            dr["PRODUCT_SPEC_OUT"] = mProduct.ProductSpecOut;
            //            dr["MATERIAL"] = mProduct.Material;
            //            dr["DIAMETER_OUT"] = mProduct.DiameterOut;
            //            dr["DIAMETER_IN"] = mProduct.DiameterIn;
            //            dr["LENGTH"] = mProduct.Length;
            //            dr["UNIT"] = mProduct.Unit;
            //            dr["REGISTER_ITEM_ID"] = frm.SelectedRepRegisterItem.RegisterItemId;
            //        }
            //    }
            //}
            //else
            //{

            //}
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("PRICE") || e.Column.FieldName.Equals("QTY"))
            {
                ResetTotalAmount();
            }
        }

        private void cboxIsTax_CheckedChanged(object sender, EventArgs e)
        {
            if (cboxIsTax.Checked)
            {
                gridView1.Columns["PRICE"].Caption = "单价（含税）";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计（含税）";
                ResetTax();
            }
            else
            {
                gridView1.Columns["PRICE"].Caption = "单价";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计";
                ResetTax();
            }
        }

        #endregion

        private void btnContactQuery_Click(object sender, EventArgs e)
        {
            frmMaintainSalesOrderQuery frm = new frmMaintainSalesOrderQuery(true);
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK && frm.SelectedSalesOrderList != null && frm.SelectedSalesOrderList.Count > 0)
            {
                lboxContact.Tag = frm.SelectedSalesOrderList;
                lboxContact.Items.Clear();
                foreach (SalesOrderEntity entity in frm.SelectedSalesOrderList)
                {
                    if (entity == null)
                    {
                        continue;
                    }
                    lboxContact.Items.Add(entity.OrderCode);
                }
            }
            else
            {
                lboxContact.Tag = null;
                lboxContact.Items.Clear();
            }
            SetDataGridDetailByListBox();
        }
    }
}
